/**
 *
 */
package com.meetablog.util;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.TimeZone;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.text.DecimalFormat;

import net.sf.json.JSONArray;

public class Util {

	private static String key = "nsekglobal";
	private static String iv = "4843573375";
	//private static String key = "123";
	//private static String iv = "456";
	private static String enc = null;
	private static String dec = null;
	
	private String	retVal;
	private int	retInt;

	public static String getCSRF() {
		String csrfToken = "";
		String str = "Q1W2E3R4T5Y6U7I8O9P0L0K9J8H7G6F5D4S3A2Z1X1C2V3B4N5M6";
		Random ran = new Random();
		for (int i = 0; i < 20; i++) {
			int num = ran.nextInt(51);
			csrfToken += str.substring(num, num + 1);
		}
		return csrfToken;
	}

	public static String setUTF(String str) throws UnsupportedEncodingException {
		return new String(Util.filter(str).getBytes("8859_1"), "UTF-8");
	}

	public static String getNowDate() {
		SimpleDateFormat sdf = new SimpleDateFormat();
		sdf.applyPattern("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Asia/Seoul"));
		return sdf.format(cal.getTime());
	}

	public static String getNowDate(int day) { //오늘 날짜에서 day만큼 더하거나 빼기
		SimpleDateFormat sdf = new SimpleDateFormat();
		sdf.applyPattern("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Asia/Seoul"));
		cal.add(Calendar.DATE, day);
		return sdf.format(cal.getTime());
	}

	public static String getNowDate(int year, int month, int day, int y, int m, int d) { //오늘 날짜에서 day만큼 더하거나 빼기
		GregorianCalendar date = new GregorianCalendar(year, month, day);
		date.add(Calendar.YEAR, y);
		date.add(Calendar.MONTH, m);
		date.add(Calendar.DATE, d);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	    return sdf.format(date.getTime());
	}

	public static String getNowTime() {
		java.util.Date today = Calendar.getInstance().getTime();
		SimpleDateFormat formatter = new SimpleDateFormat("HHmm");
		return formatter.format(today);
	}

	public static String getNowTime2() {
		java.util.Date today = Calendar.getInstance().getTime();
		SimpleDateFormat formatter = new SimpleDateFormat("HHmmss");
		return formatter.format(today);
	}

	public static String getNowTime3() {
		java.util.Date today = Calendar.getInstance().getTime();
		SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
		return formatter.format(today);
	}

	public static String getNowDateTime() {
		java.util.Date today = Calendar.getInstance().getTime();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		return formatter.format(today);
	}

	public static String getTomorrow() {
		Date today = new Date();
		Date tomorrow = new Date();
		tomorrow.setTime(today.getTime()+((long)1000*60*60*24));
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
		return formatter.format(tomorrow);
	}

	public static int getNowWeekday() {
		Calendar cal = Calendar.getInstance();
		return cal.get(Calendar.DAY_OF_WEEK);
	}

	public static String getNowDateFormat(String format) {
		java.util.Date today = Calendar.getInstance().getTime();
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		return formatter.format(today);
	}

	public static String getNowHour() {
		SimpleDateFormat sdf = new SimpleDateFormat();
		sdf.applyPattern("hh");
		Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Asia/Seoul"));
		return sdf.format(cal.getTime());
	}

	public static String makeYear(String year) {
		String sOption = "";
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		int aiSearchYear = Integer.parseInt(sdf.format(date));
		if (year != null) {
			for (int loopYear = aiSearchYear - 2; loopYear <= aiSearchYear; loopYear++) {
				sOption += "<option value ='"
						+ loopYear
						+ "' "
						+ (Integer.parseInt(year) == loopYear ? " selected='selected' >"
								: " >") + loopYear + "</option>\n";
			}
		} else {
			for (int loopYear = aiSearchYear - 2; loopYear <= aiSearchYear; loopYear++) {
				sOption += "<option value ='" + loopYear + "' "
						+ (aiSearchYear == loopYear ? " selected='selected' >" : " >")
						+ loopYear + "</option>\n";
			}
		}
		return sOption;
	}

	public static String makeYear2(String year) {
		String sOption = "";
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		int aiSearchYear = Integer.parseInt(sdf.format(date));
		if (year != null) {
			for (int loopYear = aiSearchYear; loopYear <= aiSearchYear + 2; loopYear++) {
				sOption += "<option value ='"
						+ loopYear
						+ "' "
						+ (Integer.parseInt(year) == loopYear ? " selected='selected' >"
								: " >") + loopYear + "</option>\n";
			}
		} else {
			for (int loopYear = aiSearchYear; loopYear <= aiSearchYear + 2; loopYear++) {
				sOption += "<option value ='" + loopYear + "' "
						+ (aiSearchYear == loopYear ? " selected='selected' >" : " >")
						+ loopYear + "</option>\n";
			}
		}
		return sOption;
	}

	public static String makeMonth(String month) {
		String sOption = "";
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("MM");
		int aiSearchMonth = Integer.parseInt(sdf.format(date));
		if (month != null) {
			for (int loopMonth = 1; loopMonth <= 12; loopMonth++) {
				sOption += "<option value ='"
						+ (loopMonth < 10 ? "0" : "")
						+ loopMonth
						+ "' "
						+ (Integer.parseInt(month) == loopMonth ? " selected='selected' >"
								: " >") + (loopMonth < 10 ? "0" : "")
						+ loopMonth + "</option>\n";
			}
		} else {
			for (int loopMonth = 1; loopMonth <= 12; loopMonth++) {
				sOption += "<option value ='" + (loopMonth < 10 ? "0" : "")
						+ loopMonth + "' "
						+ (aiSearchMonth == loopMonth ? " selected='selected' >" : " >")
						+ (loopMonth < 10 ? "0" : "") + loopMonth
						+ "</option>\n";
			}
		}
		return sOption;
	}

	public static String makeDay(String day) {
		String sOption = "";
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("dd");
		int aiSearchDay = Integer.parseInt(sdf.format(date));
		if (day != null) {
			for (int loopDay = 1; loopDay <= 31; loopDay++) {
				sOption += "<option value ='"
						+ (loopDay < 10 ? "0" : "")
						+ loopDay
						+ "' "
						+ (loopDay == Integer.parseInt(day.trim()) ? " selected='selected' >"
								: " >") + (loopDay < 10 ? "0" : "") + loopDay
						+ "</option>\n";
			}
		} else {
			for (int loopDay = 1; loopDay <= 31; loopDay++) {
				sOption += "<option value ='" + (loopDay < 10 ? "0" : "")
						+ loopDay + "' "
						+ (aiSearchDay == loopDay ? " selected='selected' >" : " >")
						+ (loopDay < 10 ? "0" : "") + loopDay + "</option>\n";
			}
		}
		return sOption;
	}

	public static String makeDay2(String day) {
		String sOption = "";
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("dd");
		int aiSearchDay = Integer.parseInt(sdf.format(date));
		if (day != null) {
			for (int loopDay = 1; loopDay <= 31; loopDay++) {
				sOption += "<option value ='" + (loopDay < 10 ? "0" : "")
						+ loopDay + "'  >" + (loopDay < 10 ? "0" : "")
						+ loopDay + "</option>\n";
			}
		} else {
			for (int loopDay = 1; loopDay <= 31; loopDay++) {
				sOption += "<option value ='" + (loopDay < 10 ? "0" : "")
						+ loopDay + "' "
						+ (aiSearchDay == loopDay ? " selected='selected' >" : " >")
						+ (loopDay < 10 ? "0" : "") + loopDay + "</option>\n";
			}
		}
		return sOption;
	}

	public static String getCommaNum(Long amount) {
		NumberFormat nf = NumberFormat.getIntegerInstance();
		return nf.format(amount);
	}

	public static String getCommaNum(Double amount) {
		NumberFormat nf = NumberFormat.getIntegerInstance();
		return nf.format(amount);
	}

	public static String paging(int count, int currentPages, int blockSize,
			String linkUrl, String method) {
		String result = "";
		method = "".equals(method)?"goPage":method;
		if (count > 0) {
			int totalPage = count / blockSize
					+ (count % blockSize == 0 ? 0 : 1);
			int prev = (int) Math.floor((currentPages - 1) / blockSize) * blockSize;
			int next = prev + (blockSize + 1);
			
			/*			
			result += "<div>\n";
			result += "<input type='text' name='page' value='"+prev+"'>\n";
			if (queryStr.indexOf("&") >= 0) {
				String arrQuery[] = queryStr.split("&");
				for (int j = 0; j < arrQuery.length; j++) {
					if (queryStr.indexOf("=") >= 0) {
						String arrParams[] = arrQuery[j].split("=");
						if (arrParams.length > 1) {
							result += "<input type='text' name='"+arrParams[0]+"' value='"+arrParams[1]+"'/>\n";
						}
					}
				}
			}
			result += "</div>\n";
			
			
			result += "<div>\n";
			result += "<input type='text' name='page' value='"+next+"'>\n";
			
			if (queryStr.indexOf("&") >= 0) {
				String arrQuery[] = queryStr.split("&");
				for (int j = 0; j < arrQuery.length; j++) {
					if (queryStr.indexOf("=") >= 0) {
						String arrParams[] = arrQuery[j].split("=");
						if (arrParams.length > 1) {
							result += "<input type='text' name='"+arrParams[0]+"' value='"+arrParams[1]+"'/>\n";
						}
					}
				}
			}
			result += "</div>\n";
			
			for (int i = prev + 1; i < next && i <= totalPage; i++) {
				if (i == currentPages) {
				} else {
					result += "<div>\n";
					result += "<input type='text' name='page' value='"+i+"'/>\n";
					if (queryStr.indexOf("&") >= 0) {
						String arrQuery[] = queryStr.split("&");
						for (int j = 0; j < arrQuery.length; j++) {
							if (queryStr.indexOf("=") >= 0) {
								String arrParams[] = arrQuery[j].split("=");
								if (arrParams.length > 1) {
									result += "<input type='text' name='"+arrParams[0]+"' value='"+arrParams[1]+"'/>\n";
								}
							}
						}
					}
					result += "</div>\n";
				}
			}
			*/
			result += "<div class='paging'>\n";
			if (prev > 0) {
				result += "<a href='#' class='pre' name='"+method+"' startRow="+((prev) - blockSize)+" currentPage='"+prev+"' >";
				result += "prev</a>\n";
			}
			for (int i = prev + 1; i < next && i <= totalPage; i++) {
				if (i == currentPages) {
					result += "<a href='#' class='num' name='"+method+"' startRow='"+((i*blockSize)-blockSize)+"' currentPage='"+i+"' style='border: 1px solid #9BD3E3; background: #DFEDF0;color:#0000ff;'>"
							+ i + "</a>\n";
				} else {
					result += "<a href='#' class='num' name='"+method+"' startRow='"+((i*blockSize)-blockSize)+"' currentPage='"+i+"' >"+i+"</a>\n";
				}
			}
			if (next <= totalPage) {

				result += "<a href='#' class='next' name='"+method+"' startRow="+((next*blockSize) - blockSize)+" currentPage='"+next+"' >";
				result += "next</a>\n";
			}
			result += "</div>\n";
		}
		
		return result;
	}

	public static String getYYYY() {
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		String result = sdf.format(date);
		return result;
	}

	public static String getMM() {
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("MM");
		String result = sdf.format(date);
		return result;
	}

	public static String getDecimalFormat(double NumberValue, String FormatValue) {
		DecimalFormat exFormat = new DecimalFormat(FormatValue);
		String result = exFormat.format(NumberValue);
		return result;
	}

	public static String filter(String str) {
		String filterStr = "union/delete /select /update /variable/"
				+ "openrowset/drop column/alter table/alter column/alert/create /insert /;--/) --/'='/' = '/declare/"
				+ "exec/seq@/</>/iframe/frame/script/style/import/sysobject/drop/$/\\/\'/\"/|/sp_/xp_/{(select)}/" +
						"{(insert)}/{(update)}/{(delete)}/{(drop)}/{(union)}/{(sp_)}/{(xp_)}/{(sysobject)}/\"\'/*/img src/1=1/1 = 1/.html/.htm/IMG+SRC/+and+";
		String filterArr[] = filterStr.split("/");
		for (int i = 0; i < filterArr.length; i++) {
			if (str != null
					&& (str.indexOf(filterArr[i]) >= 0 || str
							.indexOf(filterArr[i].toUpperCase()) >= 0)) {
				str = str.replace(filterArr[i], "");
				str = str.replace(filterArr[i].toUpperCase(), "");
			}
		}
		return str;
	}

	public static int whichDay(String s, String format)
			throws java.text.ParseException {
		java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(
				format, java.util.Locale.KOREA);
		java.util.Date date = check(s, format);

		java.util.Calendar calendar = formatter.getCalendar();
		calendar.setTime(date);
		return calendar.get(java.util.Calendar.DAY_OF_WEEK);
	}

	public static String addDays(String s, int day, String format) throws java.text.ParseException{
		java.text.SimpleDateFormat formatter =
			new java.text.SimpleDateFormat (format, java.util.Locale.KOREA);
		java.util.Date date = check(s, format);
		date.setTime(date.getTime() + ((long)day * 1000 * 60 * 60 * 24));
		return formatter.format(date);
	}

	public static String addMonths(String s, int addMonth, String format) throws Exception {
		java.text.SimpleDateFormat formatter =
			new java.text.SimpleDateFormat (format, java.util.Locale.KOREA);
		java.util.Date date = check(s, format);

		java.text.SimpleDateFormat yearFormat =
			new java.text.SimpleDateFormat("yyyy", java.util.Locale.KOREA);
		java.text.SimpleDateFormat monthFormat =
			new java.text.SimpleDateFormat("MM", java.util.Locale.KOREA);
		java.text.SimpleDateFormat dayFormat =
			new java.text.SimpleDateFormat("dd", java.util.Locale.KOREA);
		int year = Integer.parseInt(yearFormat.format(date));
		int month = Integer.parseInt(monthFormat.format(date));
		int day = Integer.parseInt(dayFormat.format(date));

		month += addMonth;
		if (addMonth > 0) {
			while (month > 12) {
				month -= 12;
				year += 1;
			}
		} else {
			while (month <= 0) {
				month += 12;
				year -= 1;
			}
		}
		java.text.DecimalFormat fourDf = new java.text.DecimalFormat("0000");
		java.text.DecimalFormat twoDf = new java.text.DecimalFormat("00");
		String tempDate = String.valueOf(fourDf.format(year))
		+ String.valueOf(twoDf.format(month))
		+ String.valueOf(twoDf.format(day));
		java.util.Date targetDate = null;

		try {
			targetDate = check(tempDate, "yyyyMMdd");
		} catch(java.text.ParseException pe) {
			day = lastDay(year, month);
			tempDate = String.valueOf(fourDf.format(year))
			+ String.valueOf(twoDf.format(month))
			+ String.valueOf(twoDf.format(day));
			targetDate = check(tempDate, "yyyyMMdd");
		}

		return formatter.format(targetDate);
	}

	public static String addYears(String s, int year, String format) throws java.text.ParseException {
		java.text.SimpleDateFormat formatter =
			new java.text.SimpleDateFormat (format, java.util.Locale.KOREA);
		java.util.Date date = check(s, format);
		date.setTime(date.getTime() + ((long)year * 1000 * 60 * 60 * 24 * (365 + 1)));
		return formatter.format(date);
	}

	public static int lastDay(int year, int month) throws java.text.ParseException {
		int day = 0;
		switch(month)
		{
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12: day = 31;
		break;
		case 2: if ((year % 4) == 0) {
			if ((year % 100) == 0 && (year % 400) != 0) { day = 28; }
			else { day = 29; }
		} else { day = 28; }
		break;
		default: day = 30;
		}
		return day;
	}

	public static java.util.Date check(String s, String format)
			throws java.text.ParseException {
		if (s == null)
			throw new java.text.ParseException("date string to check is null",
					0);
		if (format == null)
			throw new java.text.ParseException(
					"format string to check date is null", 0);

		java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(
				format, java.util.Locale.KOREA);
		java.util.Date date = null;
		try {
			date = formatter.parse(s);
		} catch (java.text.ParseException e) {
			/*
			 * throw new java.text.ParseException( e.getMessage() + " with
			 * format \"" + format + "\"", e.getErrorOffset() );
			 */
			throw new java.text.ParseException(" wrong date:\"" + s
					+ "\" with format \"" + format + "\"", 0);
		}

		if (!formatter.format(date).equals(s))
			throw new java.text.ParseException("Out of bound date:\"" + s
					+ "\" with format \"" + format + "\"", 0);
		return date;
	}

	//문자열자르는 메소드
	public static String cutStr(String str, int i, String tail) {
		if (str == null)
			return "";
		String tmp = str;
		int slen = 0, blen = 0;
		char c;
		if (tmp.getBytes().length > i) {
			while (blen + 1 < i) {
				c = tmp.charAt(slen);
				blen++;
				slen++;
				if (c > 127)
					blen++; // 2-byte character..
			}
			tmp = tmp.substring(0, slen) + tail;
		}else{
			tmp = str;
		}
		return tmp;

	}

	public static String getTerm(String passDate, String nowDate) throws java.text.ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date1 = sdf.parse(nowDate);
		Date date2 = sdf.parse(passDate);
		long a=date1.getTime(); //밀리세컨드로 변환
		long b=date2.getTime(); //밀리세컨드로 변환
		long c=a-b;
		long term= c / (1000*60*60*24) + 1;
		return String.valueOf(term);
	}
	
	
	public String getStr(Object obj){

		if(null==obj){

			retVal = "";

		} else {
			
			retVal = obj.toString();

		}
		
		return retVal;
	}

	public int getInt(Object obj){
		
		if(null==obj){
			
			retInt = 0;
			
		} else {
			
			retInt = Integer.parseInt(obj.toString());
		}
		
		return retInt;
	}
	
    public static String clobToString(Clob clob) throws SQLException, IOException {

		if (clob == null) {
			return "";
		} 
		   
		StringBuffer strOut = new StringBuffer();
		String str = "";
		BufferedReader br = new BufferedReader(clob.getCharacterStream());
		
		while ((str = br.readLine()) != null) {
			strOut.append(str);
		}
			return strOut.toString();
		} 	
	
	public JSONArray makeJsonResult(ArrayList sqlMap) {
		
		System.out.println("sql =============> " + sqlMap);
		System.out.println("jsonArray start");
		
		JSONArray jsonArray = JSONArray.fromObject(sqlMap); 		//ArrayList 속성을 json객체로
		
		System.out.println("jsonArray end");
		
		/*
		
		while(rs.next()){
			
			Map rsMap =  new HashMap();
			
			for( int i = 1 ; i <= columnCount; i++){
				rsMap.put("" +rsmd.getColumnName(i)+"", ""+rs.getObject(j)+"");
				j++;
			}
			list.add(rsMap);
			j = 1;
		}
		*/
		
		//JSONObject jsonObjet = JSONObject.fromObject(sqlMap); //HashMap 속성을 json 객체로

        //JSONArray jsonArray = JSONArray.fromObject(sqlMap); //ArrayList 속성을 json객체로
	        
	
		//System.out.println(jsonArray);
		//System.out.println(jsonObjet);
		System.out.println("jsonArray =============> " + jsonArray + "\n\n\n");
		
		return jsonArray;
	}

	

	
}
